﻿using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;
using ApplicationLibrary;
using ApplicationLibrary.DBManager;
using ApplicationLibrary.ExtendedControls;
using ApplicationLibrary.SqlConnector;
using Vintner.Items.ModuleData;
using Vintner.Masters.ModuleData;

namespace Vintner.Items.Forms
{
    public partial class Items : ApplicationLibrary.DBManager.DocumentForm
    {
        private DRDescriptions dRCategory = null;

        public Items()
            : base("Items")
        {
            InitializeComponent();
            keyControl = codItem;
        }

        #region Virtual Method

        protected override IRadarParameters GetKeyFromDocument()
        {
            return new RadarItemsParam(codItem.Text);
        }

        protected override void OnAttachData()
        {
            dbManager = new dbmanagerItems("itemsForm", new RadarItemsForm(), this);
            dbManager.AddMaster(this, VI_Items.Name, true);
            dbManager.AddSlave(VI_ItemsPrice.Name, true);
            dbManager.AddRelation("ItemPrice", VI_Items.Item, VI_ItemsPrice.Item, true);

            dRCategory = new DRDescriptions(DescriptionType.E_Category);

            codItem.AttachCodeType("Items");
            colCategory.AttachDataReader(new RRDescriptions(DescriptionType.E_Category), VI_Descriptions.Code, VI_Descriptions.Description);
            colTaxCode.AttachDataReader(new RRTaxCode(), VI_TaxCode.Code, VI_TaxCode.Description);

            dgwPrice.AutoGenerateColumns = false;
            dgwPrice.DataSource = dbManager.SlaveBinding("ItemPrice");

            dgwPrice.AddColumnValidator(VI_ItemsPrice.Category, new ExtendedDataGridView.DataGridViewColumnValidatingEventHandler(ItemPrice_CategoryValidating));
        }

        protected override void OnBindData()
        {
            BindControl(codItem, VI_Items.Item, NullValue.NotSet, Findable.YES);
            BindControl(txtDescription, VI_Items.Description, Findable.YES);
            BindControl(ntbSize, VI_Items.Size);
            BindControl(ckbDisabled, VI_Items.Disabled, "DBChecked");

            BindColumn(colCategory, VI_ItemsPrice.Category);
            BindColumn(colPrice, VI_ItemsPrice.Price);
            BindColumn(colTaxCode, VI_ItemsPrice.TaxCode);
            BindColumn(colDisable, VI_ItemsPrice.Disabled);
            
            BindControl(dgwPrice);
        }

        protected override void OnDisableControlsForEdit()
        {
            codItem.Enabled = false;
            base.OnDisableControlsForEdit();
        }

        protected override void FocusOnNew()
        {
            codItem.Focus();
        }

        protected override bool OnBeforeSave()
        {
            return base.OnBeforeSave();
        }

        #endregion

        private string ItemPrice_CategoryValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (dbManager.Status != DBMode.Edit)
                return "";

            string curCat = e.FormattedValue.ToString();

            foreach (DataGridViewRow dr in dgwPrice.Rows)
            {
                if (dr.Index != e.RowIndex && !dr.IsNewRow)
                {
                    dRCategory.Find(DataGridViewRowValues.GetValue<string>(dr, VI_ItemsPrice.Category));
                    string rowCat = dRCategory.GetValue<string>(VI_Descriptions.Description);
                    if (rowCat == curCat)
                    {
                        e.Cancel = true;
                        return Properties.Resources.Msg_DuplicateCat;
                    }
                }
            }
            return "";
        }
    }

    #region DbManager dbmanagerItems

    /// <summary>
    /// Classe derivata per gestioni particolari
    /// </summary>
    internal class dbmanagerItems : DBManager
    {
        public dbmanagerItems(string name, RadarForm radar, DocumentForm document)
            : base(name, radar, document)
        {
            ForeignKey = VI_Items.Item;
        }

        protected override void dAdapter_MasterRowUpdating(object sender, SqlABRowUpdatingEventArgs e)
        {
            base.dAdapter_MasterRowUpdating(sender, e);
        }

        protected override void dAdapter_RowUpdating(object sender, SqlABRowUpdatingEventArgs e)
        {
            if (e.StatementType == StatementType.Insert)
            {
                e.Row[VI_ItemsPrice.Item.Name] = GetColumn<string>(VI_Items.Item, Pos);
            }
            base.dAdapter_RowUpdating(sender, e);
        }

        protected override string CreateMasterQuery()
        {
            this.Table = new VI_Items();
            QueryBuilder qB = new QueryBuilder();
            qB.AddSelect();
            qB.AddFrom(VI_Items.Name);
            qB.AddCompare(VI_Items.Item, "@p1");

            return qB.Query;
        }

        protected override List<SqlABParameter> CreateMasterParam()
        {
            List<SqlABParameter> PList = new List<SqlABParameter>();

            SqlABParameter sParam = new SqlABParameter("@p1", VI_Items.Item);
            sParam.Value = VI_Items.Item.DefaultValue;
            PList.Add(sParam);
            return PList;
        }

        protected override string CreateSlaveQuery(string name)
        {
            if (name == VI_ItemsPrice.Name)
            {
                QueryBuilder qB = new QueryBuilder();
                qB.AddSelect();
                qB.AddFrom(VI_ItemsPrice.Name);
                qB.AddCompare(VI_ItemsPrice.Item, "@p2");
                qB.AddOrder(VI_ItemsPrice.Category);
                return qB.Query;
            }
            return "";
        }

        protected override List<SqlABParameter> CreateSlaveParam(string name)
        {
            if (name == VI_ItemsPrice.Name)
            {
                List<SqlABParameter> PList = new List<SqlABParameter>();

                SqlABParameter sParam = new SqlABParameter("@p2", VI_ItemsPrice.Item);
                sParam.Value = VI_ItemsPrice.Item.DefaultValue;
                PList.Add(sParam);
                return PList;
            }
            return null;
        }

        protected override void SetParameters(IRadarParameters key, DBCollection collection)
        {
            // if (collection.Name == VI_Items.Name)
            collection.Parameter[0].Value = key[0];
        }
    }

    #endregion
}